package org.ghost.spring.cloud.consumer.demo.controller;


import org.ghost.spring.cloud.consumer.demo.common.component.RequestContext;
import org.ghost.spring.cloud.consumer.demo.common.component.RspDTOFactory;
import org.ghost.spring.cloud.consumer.demo.common.constant.SystemErrorCodeEnum;
import org.ghost.spring.cloud.consumer.demo.dto.RspDTO;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * 控制器抽象类
 */
abstract public class BaseController {
    @Resource
    protected HttpServletRequest request;

    @Resource
    protected HttpServletResponse response;

    private static final String DEFAULT_PARAM_FIELD_ERROR_SUFFIX = "不存在";

    protected RspDTO renderParamFieldError(String paramField) {
        return new RspDTO(SystemErrorCodeEnum.PARAM_ERROR.getCode(), String.format("%s: %s", DEFAULT_PARAM_FIELD_ERROR_SUFFIX, paramField));
    }

    protected RspDTO renderErrorParamError() {
        return RspDTOFactory.getParamErrorRspDTO();
    }

    protected RspDTO renderErrorNoPermission() {
        return RspDTOFactory.getNoPermissionRspErrorDTO();
    }

    /**
     * 渲染成功数据
     *
     * @return RspDTO
     */
    protected RspDTO render() {
        return new RspDTO(true);
    }

    /**
     * 渲染数据
     *
     * @param object 返回数据
     * @return RspDto
     */
    protected RspDTO render(Object object) {
        return new RspDTO(object);
    }


    /**
     * 渲染错误信息
     *
     * @param code    错误码
     * @param message 错误信息
     * @return RspDto
     */
    protected RspDTO render(String code, String message) {
        return new RspDTO(code, message);
    }

    protected Locale getDefaultLocale() {
        Locale locale = RequestContext.getContext().getLocale();
        if (locale == null) {
            locale = Locale.SIMPLIFIED_CHINESE;
        }
        return locale;
    }

    /**
     * 渲染成功数据
     *
     * @return
     */
    protected RspDTO getSuccess() {
        return this.render();
    }

    /**
     * 渲染成功数据
     *
     * @param object
     * @return
     */
    protected RspDTO getFromData(Object object) {
        return this.render(object);
    }
}
